package com.itheima.反射.field.demo2;

import com.itheima.反射.field.demo1.Student;

import java.lang.reflect.Field;

public class Demo {
    public static void main(String[] args) throws Exception {
        //获取class字节码文件对象
        Class<?> aClass = Class.forName("com.itheima.反射.field.demo1.Student");

        //获取name这个Field对象
        Field field = aClass.getField("name");

        //利用set方法赋值
        //先创建对象
        Student stu = (Student) aClass.newInstance();
        //赋值
        field.set(stu,"zhangsan");
        System.out.println(stu);
        method2(aClass);


    }

    private static void method2(Class<?> aClass) throws NoSuchFieldException, InstantiationException, IllegalAccessException {
        //获取成员变量Field的对象
        Field declaredField = aClass.getDeclaredField("money");

        //取消访问检查
        declaredField.setAccessible(true);

        //调用set方法给指定对象赋值
        //获取一个对象
        Student student = (Student) aClass.newInstance();
        //为指定对象赋值
        declaredField.set(student,500);

        System.out.println(student);
    }
}
